import axios from 'axios'
import router from '@/router'
import { BASE_URL } from '@/api/config.js'

const request = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? BASE_URL
      : '/api',
  timeout: 120000
})

// 拦截器
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const user = localStorage.getItem('token')
    // const user = JSON.parse(
    //   window.localStorage.getItem('user')
    // )
    // console.log(localStorage.getItem('token'))
    if (user) {
      config.headers.AUTH_TOKEN = user
    }
    // if (user && user.token) {
    //   config.headers['x-token'] = user.token
    // }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // if (response && response.status === 401) {
    //   localStorage.clear()
    // } else {
    return response.data
    // }
    // 对响应数据做点什么
  },
  function (error) {
    const status = error.response.status
    if (status === 401) {
      localStorage.removeItem('menu')
      localStorage.removeItem('btnAuth')
      localStorage.removeItem('token')
      localStorage.removeItem('userName')
      localStorage.removeItem('deptName')
      localStorage.removeItem('status')
      localStorage.removeItem('userId')
      localStorage.removeItem('camera')
      router.replace('/login')
    }
    console.log(error.response.status, 'response')
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export default request
